package com.idea.relax.exception.config;

import com.idea.relax.exception.core.manager.ErrorCodeManager;
import com.idea.relax.exception.core.registry.IErrorCodeRegister;
import com.idea.relax.exception.error.BaseExceptionTranslator;
import com.idea.relax.exception.core.registry.AutoErrorCodeRegister;
import com.idea.relax.exception.core.registry.IErrorCodeCollector;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * @author: 沉香
 * @date: 2023/2/27
 * @description: 异常工具包的自动配置类
 */
@Order
@Configuration(
	proxyBeanMethods = false
)
@EnableConfigurationProperties(ExceptionKitProperties.class)
public class ExceptionKitAutoConfiguration implements InitializingBean {

	private MessageSource messageSource;

	/**
	 * 注入全局异常处理器
	 * @param properties 配置类
	 * @return 全局异常处理器
	 */
	@Bean
	@ConditionalOnMissingBean
	public BaseExceptionTranslator baseExceptionTranslator(ExceptionKitProperties properties) {
		return new BaseExceptionTranslator(properties);
	}

	/**
	 * 注入异常码注册器
	 * @param objectProvider 自定义异常码的收集器
	 * @param properties 配置类
	 * @return 异常码注册器
	 */
	@Bean
	@ConditionalOnMissingBean
	public IErrorCodeRegister errorCodeRegister(ObjectProvider<IErrorCodeCollector> objectProvider, ExceptionKitProperties properties) {
		return new AutoErrorCodeRegister(objectProvider.getIfAvailable(), properties);
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		ErrorCodeManager.setMessageSource(messageSource);
	}

}
